package ruler.rules.storage;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.File;

import ruler.rules.Rule;
import ruler.rules.andRule;
import ruler.rules.appRunningRule;
import ruler.rules.composedRule;
import ruler.rules.notRule;
import ruler.rules.orRule;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class RulesStore {
	
	private final static String FILE_NAME = "/data/data/ruler.main/ruleStore.txt";
	
	public RulesStore() {
	}

	public static XStream setPharser() {
		XStream pharseador = new XStream();
		pharseador = new XStream(new DomDriver());
		pharseador.setMode(XStream.ID_REFERENCES);
		pharseador.alias("RulesHash", RulesHash.class);
		pharseador.alias("Rule", Rule.class);
		pharseador.alias("ComposedRule", composedRule.class);
		pharseador.alias("AndRule", andRule.class);
		pharseador.alias("OrRule", orRule.class);
		pharseador.alias("NotRule", notRule.class);
		pharseador.alias("appRunningRule", appRunningRule.class);
		return pharseador;
	}

	public static RulesHash Load() {
		RulesHash rules = new RulesHash();
		XStream pharseador = setPharser();
		try {
			FileInputStream fOut = new FileInputStream(FILE_NAME);
			InputStreamReader osw = new InputStreamReader(fOut);
			char[] inputBuffer = new char[(char) new File(FILE_NAME).length()];
			osw.read(inputBuffer);
			String g = new String(inputBuffer);
			rules = (RulesHash) pharseador.fromXML(g);
			return rules;
		} catch (IOException ioe2) {
			return rules;
		}
	}

	public static void Save(RulesHash rules) {
		XStream pharseador = setPharser();
		String xml = pharseador.toXML(rules);
		try {
			FileOutputStream fOut = new FileOutputStream(FILE_NAME);
			OutputStreamWriter osw = new OutputStreamWriter(fOut);
			osw.write(xml);
			osw.flush();
			osw.close();
		} catch (IOException ioe2) {
		}
	}
	
}
